package cn.com.freelibra.forum.job;
import java.util.List;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;
import static cn.com.freelibra.forum.util.StringUtil.*;
import cn.com.freelibra.forum.po.JobSetting;
import cn.com.freelibra.forum.service.JobSettingService;
@Service
public class JobAutoStartServer implements InitializingBean {

	@Autowired
	private JobSettingService jobSettingService;
	@Autowired
	private SchedulerFactoryBean schedulerFactoryBean;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		List<JobSetting> jobSettings=jobSettingService.byStatus(1);
		
		for(JobSetting jobSetting:jobSettings){
			if(isNotEmpty(jobSetting.getCornExpress())){
				Scheduler scheduler = schedulerFactoryBean.getScheduler();
				JobDetail jobDetail = JobBuilder.newJob(JobMessagQuartzJob.class).withIdentity(jobSetting.getJobName(), jobSetting.getJobGroupName())  
			                .storeDurably().build(); 
				jobDetail.getJobDataMap().put("JobSetting", jobSetting);
				CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(jobSetting.getCornExpress()); 
				CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(jobSetting.getJobName(), jobSetting.getJobGroupName())  
				                .withSchedule(scheduleBuilder).build();  
					scheduler.scheduleJob(jobDetail, trigger);
			}
				
		}
	}

}
